/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package earthdawnnet.server;

import earthdawnnet.events.client.ClientEvent;
import earthdawnnet.events.Event;
import earthdawnnet.events.server.ServerEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Andreas Franek
 */
public class ClientHandler extends Thread
{
    
    private Socket s;
    private ObjectOutputStream out;
    private ObjectInputStream in;
    private boolean doLoop = true;
    private IEarthdawnServer eds;
    private int id;

    public ClientHandler(Socket connection, IEarthdawnServer eds, int id) throws IOException
    {
        super();
        this.eds = eds;
        this.id = id;
        s = connection;
        out = new ObjectOutputStream(s.getOutputStream());
        in = new ObjectInputStream(s.getInputStream());
    }

    @Override
    public void run()
    {
        try
        {
            out.writeObject((Integer)id);
        } catch (IOException ex)
        {
            Logger.getLogger(ClientHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        while (doLoop)
        {
            try
            {
                //System.out.println("Listening for data.");
                Event ev = (Event) in.readObject();
                //System.out.println("Line received.");
                if(ev instanceof ServerEvent)
                {
                    ((ServerEvent)ev).apply(eds);
                }
            }  catch (IOException ex)
            {
                Logger.getLogger(ClientHandler.class.getName()).log(Level.SEVERE, null, ex);
                eds.logout(id);
            }catch (ClassNotFoundException ex)
            {
                Logger.getLogger(ClientHandler.class.getName()).log(Level.SEVERE, null, ex);
                eds.logout(id);
            }
        }
    }
    
    public void close()
    {
        doLoop = false;
        try
        {
            in.close();
            out.close();
            s.close();
        } catch (IOException ex)
        {
            Logger.getLogger(ClientHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void send(ClientEvent clientEvent)
    {
        try
        {
            out.writeObject(clientEvent);
        } catch (IOException ex)
        {
            Logger.getLogger(ClientHandler.class.getName()).log(Level.SEVERE, null, ex);
            eds.logout(id);
        }
    }
}
